package com.peng.leetcode.stack;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * LongestValidParentheses
 * <p>
 * 32. 最长有效括号
 *
 * @author: lupeng6
 * @create: 2021/2/4 14:46
 */
public class LongestValidParentheses {

    public static void main(String[] args) {
        String s = ")()())";
        System.out.println(new LongestValidParentheses().longestValidParentheses(s));
    }

    public int longestValidParentheses(String s) {
        int len = s.length();
        Deque<Integer> stack = new ArrayDeque<>(len);
        stack.push(-1);
        int maxLen = 0;
        for (int i = 0; i < len; i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    maxLen = Math.max(maxLen, i - stack.peek());
                }
            }
        }
        return maxLen;
    }
}
